package org.lansir.af.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.lansir.af.R;
import org.lansir.af.database.DataRowActivity;
import org.lansir.af.database.DataRowActivityParticipator;
import org.lansir.af.database.DataTable;
import org.lansir.af.database.Database;
import org.lansir.af.dataview.DataViewTrusty;
import org.lansir.af.gtalk.service.Message;
import org.lansir.af.model.ActivityMessageItem;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

public class ActivityMessageOperator {

	private static final String TAG = "ActivityMessageOperator";

	private Context mContext;

	private DataTable dataTableParticipator;
	private DataRowActivityParticipator dataRowParticipator;
	private Database userdb = null;
	private DataViewTrusty dataViewTrusty;
	private DataRowActivity dataRowActivity = null;
	private DataTable dataTableActivity = null;

	private String sMessage;
	private long lNewRowId;
	private String sContent;
	private String sPlace;
	private int iYear, iMonth, iDay, iHour, iMinute;
	private int iRingmode;
	private boolean bAlarm;
	private String sRepeat;

	public ActivityMessageOperator(Context context) {
		this.mContext = context;

		this.userdb = new Database(context);
		dataRowParticipator = new DataRowActivityParticipator(userdb);
		dataTableParticipator = new DataTable(dataRowParticipator);
		dataViewTrusty = new DataViewTrusty(userdb);
		dataViewTrusty.reloadTable();
		dataRowActivity = new DataRowActivity(userdb);
		dataTableActivity = new DataTable(dataRowActivity);
	}

	/**
	 * 判断是否是回复的格式
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isReplyFormat(String str) {
		Pattern pattern = Pattern.compile("^[0-9]*_[是|否]$");
		Matcher matcher = pattern.matcher(str.trim());
		return matcher.matches();
	}

	/**
	 * 判断是否是接收到活动的消息格式
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isReceiveActivityFormat(String str) {
		Pattern pattern = Pattern.compile("^\\[活动精灵\\].*", Pattern.DOTALL);
		Matcher matcher = pattern.matcher(str.trim());
		return matcher.matches();
	}

	public void saveSelected(ActivityMessageItem item, Handler mHandler) {
		try {

			int result = 1;
			String message = item.getBody();
			String[] msgPart = message.split("_");
			if (msgPart.length != 2)
				return;
			if (msgPart[1].endsWith("是")) {
				result = 0;
			}

			int iActivityId = Integer.parseInt(msgPart[0]);
			String[] ids = item.getContact().getJID().split("@");
			if (ids.length != 2) {
				android.os.Message msg = mHandler.obtainMessage();
				msg.arg1 = R.string.toast_save_message_failed;
				mHandler.sendMessage(msg);
				return;
			}
			boolean flag = updateActivityParticipator(iActivityId, item.getContact().getJID().toLowerCase(), result);
			Log.v(TAG, "Flag:" + flag);
			this.userdb.close();
		} catch (Exception ex) {
			android.os.Message msg = mHandler.obtainMessage();
			msg.arg1 = R.string.toast_save_message_failed;
			mHandler.sendMessage(msg);
			return;
		}

	}

	public boolean updateActivityParticipator(int iActivityId, String sParticipatorId, int iReply) {
		Log.v(TAG, "before getRowDataForEdit");
		Database.Result result = dataTableParticipator.getRowDataForEdit("ActivityId=" + iActivityId + " and ParticipatorID='" + sParticipatorId + "'");
		Log.v(TAG, "after getRowDataForEdit");
		if (result != Database.Result.Success) {
			return false;
		} else {
			dataRowParticipator.setReply(iReply);
			dataRowParticipator.setValuesForDataRow();
			dataTableParticipator.updateValuesForParticipator(iActivityId, sParticipatorId);
		}

		return false;
	}

	public void doSave(ActivityMessageItem item, Handler mHandler) {
		try {
			Log.v(TAG, "before trusty");
			if (this.dataViewTrusty.getTrusted(item.getContact().getJID().toLowerCase())) {
				Log.v(TAG, "trusty");
				saveMessage(item, mHandler);
			} else {
				Log.v(TAG, " not trusty");
				showNotification(item);

			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			this.userdb.close();
		}
	}

	private void showNotification(ActivityMessageItem item) {
		// In this sample, we'll use the same text for the ticker and the
		// expanded notification
		CharSequence text = "最新活动通知";

		NotificationManager manager = (NotificationManager) mContext.getSystemService(Service.NOTIFICATION_SERVICE);
		// Set the icon, scrolling text and timestamp
		Notification notification = new Notification(android.R.drawable.stat_notify_chat, text, System.currentTimeMillis());

		notification.flags = Notification.FLAG_AUTO_CANCEL;

		// Set the info for the views that show in the notification panel.
		notification.setLatestEventInfo(mContext, text, text, makeInformContent(item));

		// We use a layout id because it is a unique number. We use it later to
		// cancel.
		manager.notify(5, notification);
		Log.i(TAG, "notification.......show");
		// manager.cancel(0);
	}

	private PendingIntent makeInformContent(ActivityMessageItem item) {
		Intent intent = new Intent("org.lansir.af.intent.action.ACTION_MODE_VIEW_ACTIVITY_RECEIVED");
		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
		Bundle bundle = new Bundle();
		bundle.putParcelable("MessageItem", item);
		// String message = Utils.sMessage;
		// bundle.putString("message", message);
		// bundle.putString("name", item.getName());
		// bundle.putString("phone", item.getPhone());
		intent.putExtras(bundle);

		PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		return contentIntent;
	}

	private void saveMessage(ActivityMessageItem item, Handler mHandler) {
		// TODO
		// check date if no repeat
		sMessage = item.getBody();
		initContent();
		dataRowActivity.setSubject(this.sContent);
		dataRowActivity.setLocation(this.sPlace);
		Calendar calDate = Calendar.getInstance();
		calDate.set(this.iYear, this.iMonth, this.iDay, this.iHour, this.iMinute, 0);
		if (calDate.getTimeInMillis() < System.currentTimeMillis()) {
			android.os.Message msg = mHandler.obtainMessage();
			msg.arg1 = R.string.toast_activity_overdue;
			mHandler.sendMessage(msg);
			return;
		}
		Log.v("ActivityFairy", "more");
		dataRowActivity.setStartDate(calDate);

		dataRowActivity.setAlarm(this.bAlarm);

		dataRowActivity.setRingerMode(this.iRingmode);

		dataRowActivity.setOrganizer(item.getContact().getJID().toLowerCase());
		dataRowActivity.setSnooze(0);
		dataRowActivity.setSnoozeCount(0);
		setRepeat();
		dataRowActivity.setValuesForDataRow();
		dataTableActivity.updateData(true, -1);
		android.os.Message msg = mHandler.obtainMessage();
		msg.arg1 = R.string.toast_receive_trusty_message;
		mHandler.sendMessage(msg);
	}

	private void setRepeat() {
		RepeatData rd = dataRowActivity.getRepeat();
		// set repeat type
		if ("无".equals(this.sRepeat)) {
			rd.setRepeatTypeAsInt(-1);
			rd.setEvery(0);
			rd.setEndOnDate(null);
			return;
		}

		this.sRepeat = this.sRepeat.replace("每", "");
		if (this.sRepeat.contains("年")) {
			rd.setRepeatTypeAsInt(4);
			this.sRepeat = this.sRepeat.replace("年", "");
		} else if (this.sRepeat.contains("月")) {
			rd.setRepeatTypeAsInt(3);
			this.sRepeat = this.sRepeat.replace("月", "");
		} else if (this.sRepeat.contains("周")) {
			rd.setRepeatTypeAsInt(2);
			this.sRepeat = this.sRepeat.replace("周", "");
		} else if (this.sRepeat.contains("日")) {
			rd.setRepeatTypeAsInt(1);
			this.sRepeat = this.sRepeat.replace("日", "");
		}
		String[] sTemp = this.sRepeat.split("直到");
		rd.setEvery(Integer.parseInt(sTemp[0].trim()));
		SimpleDateFormat dateFormatLong = new SimpleDateFormat("yyyy-MM-dd, EEEE");
		Date date;
		try {
			if (sTemp != null && sTemp.length == 2) {
				date = dateFormatLong.parse(sTemp[1]);
				Calendar cal = Calendar.getInstance();
				cal.setTime(date);
				rd.setEndOnDate(cal);
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initContent() {
		Log.v("ActivityFairy", sMessage);

		String[] sMessageFragment = sMessage.split("\n");

		String[] sTemp = sMessageFragment[0].split(":");
		this.lNewRowId = Integer.parseInt(sTemp[1]);
		Log.v("ActivityFairy", "ID:" + lNewRowId);

		sTemp = sMessageFragment[1].split(":");
		this.sContent = sTemp[1];
		Log.v("ActivityFairy", "Content:" + sContent);
		sTemp = sMessageFragment[2].split(":");
		this.sPlace = sTemp[1];
		Log.v("ActivityFairy", "Place:" + sPlace);
		sMessageFragment[3] = sMessageFragment[3].replace("时间:", "");
		String sDate = sMessageFragment[3].substring(0, sMessageFragment[3].indexOf("("));
		String[] dateTemp = sDate.split("-");

		this.iYear = Integer.parseInt(dateTemp[0]);
		this.iMonth = Integer.parseInt(dateTemp[1]) - 1;
		this.iDay = Integer.parseInt(dateTemp[2]);

		String sTime = sMessageFragment[3].substring(sMessageFragment[3].indexOf("(") + 1, sMessageFragment[3].indexOf(")"));

		dateTemp = sTime.split(":");

		this.iHour = Integer.parseInt(dateTemp[0]);
		this.iMinute = Integer.parseInt(dateTemp[1]);

		sTemp = sMessageFragment[4].split(":");
		this.iRingmode = getRingerMode(sTemp[1]);

		sTemp = sMessageFragment[5].split(":");
		this.bAlarm = "是".equals(sTemp[1]);

		sTemp = sMessageFragment[6].split(":");
		this.sRepeat = sTemp[1];

	}

	private int getRingerMode(String sRingerMode) {
		int result = 0;
		if ("静音模式".equals(sRingerMode)) {
			result = 0;
		} else if ("振动模式".equals(sRingerMode)) {
			result = 1;
		} else if ("正常模式".equals(sRingerMode)) {
			result = 2;
		}
		return result;
	}

	@Override
	protected void finalize() throws Throwable {
		if (userdb != null)
			userdb.close();
		super.finalize();
	}

}
